//#include "track.h"

#include "sekai/Track.h"

#include <fstream>
#include <iostream>
#include <sstream>

#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/split.hpp>
#include <boost/lexical_cast.hpp>

bool Track::readFromFile(std::string fileName) {
  std::ifstream infile(fileName);

  bool header = true;
  std::string line;
  while (std::getline(infile, line)) {
    if (line == "EST_Header_End")
      header = false;
    else {
      std::vector<std::string> spl;
      boost::split(spl, line, boost::is_any_of("\t "),
                   boost::token_compress_on);
      if (header) {
        headerMap[spl[0]] = spl[1];
      } else {
        Pitch p;
        p.pos = boost::lexical_cast<double>(spl[0]);
        p.voiced = boost::lexical_cast<double>(spl[1]);
        p.f0 = boost::lexical_cast<double>(spl[2]);
        pitchTrack.push_back(p);
      }
    }
  }

  return true;
}

Pitch Track::pitchEmpty = {0};

void Track::WriteF0(
    const char *filename, int f0_length, double frame_period,
    const double *temporal_positions, const double *f0, int text_flag)
{
      std::ofstream outfile(filename);
      outfile << "EST_File Track" << std::endl;
      outfile << "DataType ascii" << std::endl;
      outfile << "NumFrames " << f0_length << std::endl;
      outfile << "FrameShift " << frame_period*0.001 << std::endl;
      outfile << "EST_Header_End" << std::endl;
      for(int i=0;i<f0_length;i++)
      {
          outfile << temporal_positions[i] << " "
                  << ((int)(f0[i]>0)) << " "
                  << f0[i] << std::endl;
      }
}
